package com.gwtprocessingjs.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/** 
 * This class demonstrates a color picker that is written mostly
 * in PDE script, with a little bit of GWT glue to retrieve
 * values from it.
 */
public class PdeColorPicker implements EntryPoint {
	
	// UI Elements.
	private final FlowPanel back = new FlowPanel();
	private final Button getColorButton = new Button("Get Color!");
	private final FlowPanel colorSwatch = new FlowPanel();
	private final Label colorLabel = new Label();
	
	@Override
	public void onModuleLoad() {
		back.add(new HTML(
				"Color picker widget written in PDE.<br><br>" +
				"Click on the color field, then click the button to update the color swatch.<br>" +
				"PDE scripts cannot push data to GWT, so the data must be pulled with a button press."));
		RootPanel.get("gwt").add(back);
		
		back.add(getColorButton);
		back.add(colorSwatch);			
		back.add(colorLabel);
		colorSwatch.setSize("100px", "100px");
		updateColor();
		
		getColorButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				updateColor();
			}
		});
	}
	
	// --- Private Methods ---
	
	/**
	 * Updates the GWT color swatch control with the color currently
	 * selected on the Processing script color picker canvas.
	 */
	private void updateColor() {
		String color = getColor();
		colorSwatch.getElement().getStyle().setBackgroundColor(color);
		colorLabel.setText(color);
	}
	
	/**
	 * Queries the Processing script to get the currently selected color.
	 * @return color currently selected in the Processing color picker
	 */
	private native String getColor() /*-{
		var myProcessing = $wnd.Processing.getInstanceById('PdeColorPicker');		
		return myProcessing.getColorValue();
	}-*/;
}
